﻿using Commission.Chart;
using Commission.DAL;
using Commission.Models;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web.Mvc;
using System.Web.Services;
using System.Web.UI.WebControls;
using Whidsoft.WebControls;

namespace OrgNodeDemo
{
	/// <summary>
    /// WebForm1
	/// </summary>
	[Authorize]
    public partial class WebForm1 : System.Web.UI.Page
	{
        private CustomerRepository db;
        private int MaxLevel = 0;
	
		protected void Page_Load(object sender, System.EventArgs e)
		{
            string rootUrl = ResolveUrl("~/");

            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect(rootUrl + "Account/Login");
            }

            bool isAdmin = User.IsInRole("Admin");

            if (this.db == null) { 
                this.db = new CustomerRepository(new SchoolContext());
            }

            string style = Request.QueryString ["style"];
            string isSponsor = Request.QueryString["sponsor"];

            int.TryParse(txtLevel.Text, out MaxLevel);
            MaxLevel = MaxLevel == 0 ? 4 : MaxLevel;

            string userName = txtUserName.Text;
            if (string.IsNullOrEmpty(userName))
            {
                userName = Request.QueryString["UserName"];
                txtUserName.Text = userName;

                NameValueCollection filtered = new NameValueCollection(Request.QueryString);
                filtered.Remove("UserName");
            }

            if ( style == null || style == "" )
            {
                style = "1";
            }

			//if ( !IsPostBack )
			//{
                Customer customer = null;

                if (!string.IsNullOrEmpty(userName))
                {
                    if (isAdmin) { 
                        customer = db.GetCustomers()
                            .Where(x => x.UserName.Equals(userName)
                                    || x.Name.Equals(userName))
                            .FirstOrDefault<Customer>();
                            ;
                    }
                    else
                    {
                        // tìm tất cả các hội viên con của user login
                        customer = db.GetCustomerByUserName(User.Identity.GetUserName());
                        IList<Customer> customers = customer.AllSubCustomers();
                        customers.Insert(0, customer);

                        customer = customers
                            .Where(x => x.UserName.Equals(userName)
                                    || x.Name.Equals(userName))
                            .FirstOrDefault<Customer>();
                        ;
                    }
                }

                if (customer == null) { 
                    customer = db.GetCustomerByUserName(User.Identity.GetUserName());
                }

                if (customer == null)
                {
                    Response.Redirect(rootUrl + "Home/Index");
                }

                IOrderedEnumerable<Customer> customerList = 
                    customer.SubCustomers.OrderBy(c => c.Position);

                MyOrgNode orgNode = new MyOrgNode();
                orgNode.Level = 1;
                orgNode.UserName = customer.UserName;
                orgNode.CustomerType = customer.CustomerType.TypeName;
                orgNode.Text = customer.Name;
                orgNode.NavigateUrl = rootUrl + "Chart/OrgChart.aspx?UserName=" + customer.UserName;
                orgNode.Description = customer.CustomerType.Point.ToString() + " Điểm"; ;
                SetNodeType(customer, orgNode);

                decimal leftPoint = GetLeftPoint(customer);
                decimal rightPoint = GetRightPoint(customer);
                orgNode.LeftPoint = Decimal.ToInt32(leftPoint);
                orgNode.RightPoint = Decimal.ToInt32(rightPoint);

                CreateNodes(customer, orgNode);

                //lblLeftPoint.Text = leftPoint.ToString();
                //lblRightPoint.Text = rightPoint.ToString();

                decimal point = leftPoint < rightPoint ? leftPoint : rightPoint;
                decimal remain = leftPoint < rightPoint ? rightPoint - leftPoint : leftPoint - rightPoint;

                //lblLeftPoint.Text = point.ToString();
                //lblRightPoint.Text = remain.ToString();

                //lblSponseredCustomer.Text = customer.SponsoredCustomers.Count.ToString();
            
                OrgChart1.Node = orgNode;

                OrgChart1.ChartStyle = (style == "1") 
                    ? Whidsoft.WebControls.Orientation.Vertical 
                    : Whidsoft.WebControls.Orientation.Horizontal;
            //}
		}

        private decimal GetLeftPoint(Customer customer)
        {
            decimal leftPoint = customer.GetPoint(1);

            decimal leftPointInDb = db.GetTotalLeftPoint(customer.CustomerID);
            decimal totalPoint = db.GetTotalHistoryPoint(customer.CustomerID);

            leftPoint = leftPoint - totalPoint - leftPointInDb;
            return leftPoint;
        }

        private decimal GetRightPoint(Customer customer)
        {
            decimal rightPoint = customer.GetPoint(2);

            decimal rightPointInDb = db.GetTotalRightPoint(customer.CustomerID);
            decimal totalPoint = db.GetTotalHistoryPoint(customer.CustomerID);

            rightPoint = rightPoint - totalPoint - rightPointInDb;

            return rightPoint;
        }

        private void CreateNodes(Customer customer, OrgNode orgNode)
        {
            try
            {
                if (customer.SubCustomers.Count < 1) return;

                if (orgNode.Level > MaxLevel) return;

                IOrderedEnumerable<Customer> customerList = 
                    customer.SubCustomers.OrderBy(c => c.Position);

                string rootUrl = ResolveUrl("~/");

                foreach (var subCustomer in customerList)
                {
                    MyOrgNode subNode = new MyOrgNode();
                    subNode.UserName = subCustomer.UserName;
                    subNode.Level = orgNode.Level + 1;
                    subNode.Text = subCustomer.Name;
                    subNode.CustomerType = subCustomer.CustomerType.TypeName;
                    subNode.NavigateUrl = rootUrl + "Chart/OrgChart.aspx?UserName=" + subCustomer.UserName;
                    subNode.Description = subCustomer.CustomerType.Point.ToString() + " Điểm";
                    SetNodeType(subCustomer, subNode);

                    decimal leftPoint = GetLeftPoint(subCustomer);
                    decimal rightPoint = GetRightPoint(subCustomer);
                    subNode.LeftPoint = Decimal.ToInt32(leftPoint);
                    subNode.RightPoint = Decimal.ToInt32(rightPoint);

                    orgNode.Nodes.Add(subNode);

                    CreateNodes(subCustomer, subNode);
                }
            }
            catch (Exception e)
            {
                //ModelErrorMessage.
                //throw;
            } 
        }

        private void SetNodeType(Customer customer, OrgNode node)
        {
            string typeName = customer.CustomerType.TypeName;
            if ("BP".Equals(typeName))
            {
                node.Type = "LOGIN";
            }
            else if ("NP".Equals(typeName) || "100F".Equals(typeName))
            {
                node.Type = "ROLES";
            }
            else if ("VP150".Equals(typeName) || "VP".Equals(typeName) || "300F".Equals(typeName))
            {
                node.Type = "GROUP";
            }
            else if ("AP700".Equals(typeName) || "AP".Equals(typeName) || "1000F".Equals(typeName))
            {
                node.Type = "ROOT";
            }
        }

		#region Web ｴnit
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
        /// InitializeComponent
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion

        [WebMethod]
        public static List<string> GetSubCustomers(string term)
        {
            List<string> City = new List<string>();
            return City;
        }
	}
}
